package com.bjpowernode.crm.web.listener;

import com.bjpowernode.crm.pojo.Value;
import com.bjpowernode.crm.service.ValueService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.*;

@WebListener
public class LoadCache implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        // 获取服务器启动成功之后创建好的Spring的工厂对象，所有实例都能通过该工厂获取
        BeanFactory beanFactory = ContextLoader.getCurrentWebApplicationContext();
        ValueService valueService = beanFactory.getBean(ValueService.class);
        List<Value> values = valueService.getAll();
        // key: 字典类型，List: 该字典类型对应的字典值
        Map<String, List> options = new HashMap<>();
        for (Value value : values) {
            List list = options.get(value.getTypeId());
            // 该类型的选项第一次在循环中出现
            if (list == null) {
                list = new ArrayList();
                options.put(value.getTypeId(), list);
            }
            list.add(value);
        }

        System.out.println(options);
        System.out.println(options);
        System.out.println(options);
        System.out.println(options);
        System.out.println(options);

        sce.getServletContext().setAttribute("options", options);


        Map possMap = new HashMap();
        ResourceBundle rb = ResourceBundle.getBundle("stage2poss");
        Enumeration<String> keys = rb.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String value = rb.getString(key);
            possMap.put(key, value);
        }
        sce.getServletContext().setAttribute("possMap", possMap);

    }
}
